package com.txy.mvnSpringbootDemo01.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;

public class SignUtil {

    // 约定的秘钥
    private static final String SECRET = "txySecretKey!@#";

    /**
     * 生成签名
     *
     * @param params 请求参数（不含 sign）
     * @return 签名字符串
     */
    public static String generateSign(Map<String, String> params) {
        // 1. 按照 key 排序
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);

        // 2. 拼接 key=value
        StringBuilder sb = new StringBuilder();
        for (String key : keys) {
            sb.append(key).append("=").append(params.get(key)).append("&");
        }
        sb.append("secret=").append(SECRET);

        // 3. 计算 SHA-256
        return sha256(sb.toString());
    }

    /**
     * SHA-256 加密
     *
     * @param str 原始字符串
     * @return 加密字符串
     */
    private static String sha256(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hash = md.digest(str.getBytes(StandardCharsets.UTF_8));
            StringBuilder hex = new StringBuilder();
            for (byte b : hash) {
                String h = Integer.toHexString(0xff & b);
                if (h.length() == 1) hex.append('0');
                hex.append(h);
            }
            return hex.toString();
        } catch (Exception e) {
            throw new RuntimeException("Error generating SHA-256 hash: ", e);
        }
    }

    public static void main(String[] args) {
        Map<String, String> params = new HashMap<>();
        params.put("username", "Tom");
        String timestamp = String.valueOf(System.currentTimeMillis());
        System.out.println("时间戳：" + timestamp);
        params.put("timestamp", timestamp);
        String sign = SignUtil.generateSign(params);
        System.out.println("签名：" + sign);
    }
}
